package com.onec.service.manage.config;

import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtil {

  /**
   * CPU核数
   **/
  private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

  private static final int MAXIMUM_POOL_SIZE = CPU_COUNT;
  /**
   * 空闲保活时限，单位秒
   */
  private static final int KEEP_ALIVE_SECONDS = 30;
  /**
   * 有界队列size
   */
  private static final int QUEUE_SIZE = 10000;

  /**
   * 创建线程池
   */
  private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
      MAXIMUM_POOL_SIZE,
      MAXIMUM_POOL_SIZE,
      KEEP_ALIVE_SECONDS,
      TimeUnit.SECONDS,
      new LinkedBlockingQueue<>(QUEUE_SIZE));

  //  优雅的关闭商户池
  static {
    executor.allowCoreThreadTimeOut(true);
    //    jvm 钩子函数 关闭线程池
  }

  /**
   * 获取线程池
   */
  public static ThreadPoolExecutor getExecutor() {
    return ThreadPoolUtil.executor;
  }


  static LinkedBlockingQueue<Future<String>> blockingQueue = new LinkedBlockingQueue<>(20);

  private static final CompletionService<String> completionService = new ExecutorCompletionService(
      executor,
      blockingQueue);

  public static CompletionService<String> getCompletionService() {
    return completionService;
  }
}
